package sy.Interceptor;

import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class MyInterceptor implements HandlerInterceptor {
	private Logger log = Logger.getLogger(this.getClass());

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
		String encoding = "UTF-8";
		// 统一设置编码格式
		request.setCharacterEncoding(encoding);
		response.setCharacterEncoding(encoding);
		response.setContentType("text/html;charset=" + encoding);
		log.debug("method=" + request.getMethod());
		log.debug(request.getQueryString());
		log.debug(request.getRemoteAddr());
		// 对Get方法做单独处理
		if (request.getMethod().equalsIgnoreCase("get")) {
			@SuppressWarnings("unchecked")
			Map<String, String[]> paramMap = request.getParameterMap();
			String[] queryStringArray = { "" };
			if (request.getQueryString() != null) {
				queryStringArray = request.getQueryString().split("&");
			}
			Set<String> keySet = paramMap.keySet();
			for (String key : keySet) {
				boolean isFromGet = false;
				for (String paramFromGet : queryStringArray) {
					if (paramFromGet.startsWith(key)) {
						isFromGet = true;
					}
				}
				if (!isFromGet) {
					continue;
				}
				String[] paramArray = (String[]) paramMap.get(key);
				for (int i = 0; i < paramArray.length; i++) {
					paramArray[i] = new String(paramArray[i].getBytes("ISO-8859-1"), encoding);
					log.info(paramArray[i]);
				}
			}
		}
		return true;
	}

	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView modelAndView) throws Exception {
		System.out.println("postHandle");
	}

	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object, Exception exception) throws Exception {
		System.out.println("afterCompletion");

	}
}
